package com.cyy.springbootinit.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import okhttp3.*;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class BigModelNew extends WebSocketListener {
    // 各版本的hostUrl及其对应的domian参数，具体可以参考接口文档 https://www.xfyun.cn/doc/spark/Web.html
    // Spark Lite      https://spark-api.xf-yun.com/v1.1/chat      domain参数为lite
    // Spark Pro       https://spark-api.xf-yun.com/v3.1/chat      domain参数为generalv3
    // Spark Pro-128K  https://spark-api.xf-yun.com/chat/pro-128k  domain参数为pro-128k
    // Spark Max       https://spark-api.xf-yun.com/v3.5/chat      domain参数为generalv3.5
    // Spark Max-32K   https://spark-api.xf-yun.com/chat/max-32k   domain参数为max-32k
    // Spark4.0 Ultra  https://spark-api.xf-yun.com/v4.0/chat      domain参数为4.0Ultra
    public static final String prompt="你是一个专注于学生宿舍水电管理的智能助手,我不要你进行知识扩展，旨在为学生提供准确、清晰、易懂的宿舍水电管理相关信息。回答学生问题时，按照下面的几点回答，不要扩展，遇到其他问题在扩展。\n" +
            "1.当学生询问宿舍水电费缴纳方式时，详细告知通过学校水电缴费系统（登录官网，点击 “水电费” 板块按提示操作）\n" +
            "2.若学生询问水电费缴纳周期，告知水电费通常每月结算一次，缴费通知会在每月月底发布，需在接到通知后的 3个工作日内完成缴费。\n" +
            "3.对于忘记缴纳水电费的后果，解释可能导致宿舍水电供应暂停，补齐欠费并提交复电 / 复水申请后，3个工作日内恢复水电供应。\n" +
            "4.学生咨询宿舍水电使用量查看方法，告知可登录学校后勤管理系统的 “宿舍水电查询” 模块或学校指定 APP 的 “水电用量” 功能进行查询。\n" +
            "5.若学生对本月水电费增多有疑问，说明可能因入住人数增加、使用大功率电器频率变高、水电设备漏水或漏电等原因，可先自行检查设备，必要时联系后勤维修人员。\n" +
            "6.当学生询问宿舍设施（如水龙头漏水、灯泡坏了）报修方式，告知可通过学校后勤报修平台（登录后选 “宿舍维修” 分类，填写宿舍号、故障描述并上传照片）或拨打后勤维修服务电话18745785412进行报修。\n" +
            "7.若学生询问报修后的维修时长，说明一般情况下 24小时内维修人员会联系确认上门时间，紧急维修（水管爆裂、电路短路等）24小时内上门。\n" +
            "8.对于维修是否收费，解释正常使用损坏免费维修，人为故意或使用不当损坏需责任人员承担费用，具体参考学校后勤管理规定。\n" +
            "9.当学生询问学校对宿舍用电功率的限制，告知单个电器功率不得超过 1000 瓦，严禁使用热得快、电火锅等违规大功率电器。\n" +
            "10.若学生询问宿舍晚上是否断电，告知学校实行夜间熄灯制度，周一至周四、周日晚上11点半 熄灯，周五、周六晚上11点 熄灯，熄灯后仅保留必要照明电源，插座电源切断，特殊情况提前通知。\n" +
            "11.学生咨询宿舍用水是否有时间限制，告知生活用水一般无限制，但热水供应有特定时间，为每天早上6点-晚上11点。\n" +
            "12.当学生询问不住校后宿舍水电费处理方式，告知办理退宿手续后，自退宿日期起不再计费，退宿前需结清已产生费用。\n" +
            "13.当学生询问你是谁时，告知我是你的专属问答助手。\n" +
            "14.若学生对水电费有疑问并询问申诉方式，告知可在接到缴费通知后的 2 个工作日内向学校后勤管理部门提出申诉，需提供质疑点和相关证据，3 个工作日内给予回复。";
    public static final String hostUrl = "https://spark-api.xf-yun.com/v4.0/chat";
    public static final String domain = "4.0Ultra";
    public static final String appid = "0bc96428";
    public static final String apiSecret = "ZjVjZTgxYmUwNDgzMTRkMzM4YjI1NWEx";
    public static final String apiKey = "1c8d525a3569d3921e24d75e1aaa6774";

    public static List<RoleContent> historyList=new ArrayList<>(); // 对话历史存储集合

    public static String totalAnswer=""; // 大模型的答案汇总

    // 环境治理的重要性  环保  人口老龄化  我爱我的祖国
    public static  String NewQuestion = "";

    public static final Gson gson = new Gson();

    // 个性化参数
    private String userId;
    private Boolean wsCloseFlag;

    private static Boolean totalFlag=true; // 控制提示用户是否输入
    // 构造函数
    public BigModelNew(String userId, Boolean wsCloseFlag) {
        this.userId = userId;
        this.wsCloseFlag = wsCloseFlag;
    }

    // 主函数
    public static void main(String[] args) throws Exception {
        // 个性化参数入口，如果是并发使用，可以在这里模拟
        while (true){
            if(totalFlag){
                Scanner scanner=new Scanner(System.in);
                System.out.print("我：");
                totalFlag=false;
                NewQuestion=scanner.nextLine();
                // 构建鉴权url
                String authUrl = getAuthUrl(hostUrl, apiKey, apiSecret);
                OkHttpClient client = new OkHttpClient.Builder().build();
                String url = authUrl.toString().replace("http://", "ws://").replace("https://", "wss://");
                Request request = new Request.Builder().url(url).build();
                for (int i = 0; i < 1; i++) {
                    totalAnswer="";
                    WebSocket webSocket = client.newWebSocket(request, new BigModelNew(i + "",
                            false));
                }
            }else{
                Thread.sleep(200);
            }
        }
    }
/*    public static String askQuestion(String newQuestion) throws Exception{
        if(totalFlag){
            totalFlag=false;
            NewQuestion=newQuestion;
            // 构建鉴权url
            String authUrl = getAuthUrl(hostUrl, apiKey, apiSecret);
            OkHttpClient client = new OkHttpClient.Builder().build();
            String url = authUrl.toString().replace("http://", "ws://").replace("https://", "wss://");
            Request request = new Request.Builder().url(url).build();
            for (int i = 0; i < 1; i++) {
                totalAnswer="";
                WebSocket webSocket = client.newWebSocket(request, new BigModelNew(i + "",
                        false));
            }
        }else{
            Thread.sleep(200);
        }
        return
    }*/
public String askQuestion(String newQuestion) throws Exception {
    System.out.println(newQuestion);
    totalFlag=true;
    if (totalFlag) {
        totalFlag = false;
        NewQuestion = newQuestion;
        // 构建鉴权url
        String authUrl = getAuthUrl(hostUrl, apiKey, apiSecret);
        OkHttpClient client = new OkHttpClient.Builder().build();
        String url = authUrl.toString().replace("http://", "ws://").replace("https://", "wss://");
        Request request = new Request.Builder().url(url).build();

        // 创建计数器用于等待响应
        CountDownLatch latch = new CountDownLatch(1);

        // 创建新的监听器实例，继承当前类并重写 onMessage 方法
        WebSocketListener listener = new BigModelNew(UUID.randomUUID().toString(), false) {
            @Override
            public void onMessage(WebSocket webSocket, String text) {
                super.onMessage(webSocket, text);
                if (gson.fromJson(text, JsonParse.class).header.status == 2) {
                    latch.countDown(); // 当接收完所有消息时释放锁
                }
            }
        };

        totalAnswer = ""; // 重置答案
        WebSocket webSocket = client.newWebSocket(request, listener);

        // 等待响应完成，设置超时时间为30秒
        boolean completed = latch.await(30, TimeUnit.SECONDS);
        if (!completed) {
            throw new RuntimeException("获取回答超时");
        }

        totalFlag = true;
        return totalAnswer;
    } else {
        throw new RuntimeException("系统正忙，请稍后再试");
    }
}

    public static boolean canAddHistory(){  // 由于历史记录最大上线1.2W左右，需要判断是能能加入历史
        int history_length=0;
        for(RoleContent temp:historyList){
            history_length=history_length+temp.content.length();
        }
        if(history_length>12000){
            historyList.remove(0);
            historyList.remove(1);
            historyList.remove(2);
            historyList.remove(3);
            historyList.remove(4);
            return false;
        }else{
            return true;
        }
    }

    // 线程来发送音频与参数
    class MyThread extends Thread {
        private WebSocket webSocket;

        public MyThread(WebSocket webSocket) {
            this.webSocket = webSocket;
        }

        public void run() {
            try {
                JSONObject requestJson=new JSONObject();

                JSONObject header=new JSONObject();  // header参数
                header.put("app_id",appid);
                header.put("uid",UUID.randomUUID().toString().substring(0, 10));

                JSONObject parameter=new JSONObject(); // parameter参数
                JSONObject chat=new JSONObject();
                chat.put("domain",domain);
                chat.put("temperature",0.5);
                chat.put("max_tokens",4096);
                parameter.put("chat",chat);

                JSONObject payload=new JSONObject(); // payload参数
                JSONObject message=new JSONObject();
                JSONArray text=new JSONArray();

                // 历史问题获取
                if(historyList.size()>0){
                    for(RoleContent tempRoleContent:historyList){
                        text.add(JSON.toJSON(tempRoleContent));
                    }
                }
                // 最新问题
                RoleContent roleContent=new RoleContent();
                RoleContent roleContent1=new RoleContent();
                roleContent1.role="system";
                roleContent1.content=prompt;
                roleContent.role="user";
                roleContent.content=NewQuestion;
                text.add(JSON.toJSON(roleContent1));
                text.add(JSON.toJSON(roleContent));
                historyList.add(roleContent);

                message.put("text",text);
                payload.put("message",message);

                requestJson.put("header",header);
                requestJson.put("parameter",parameter);
                requestJson.put("payload",payload);
                // System.err.println(requestJson); // 可以打印看每次的传参明细
                webSocket.send(requestJson.toString());
                // 等待服务端返回完毕后关闭
                while (true) {
                    // System.err.println(wsCloseFlag + "---");
                    Thread.sleep(200);
                    if (wsCloseFlag) {
                        break;
                    }
                }
                webSocket.close(1000, "");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        super.onOpen(webSocket, response);
        System.out.print("大模型：");
        MyThread myThread = new MyThread(webSocket);
        myThread.start();
    }

    @Override
    public void onMessage(WebSocket webSocket, String text) {
        // System.out.println(userId + "用来区分那个用户的结果" + text);
        JsonParse myJsonParse = gson.fromJson(text, JsonParse.class);
        if (myJsonParse.header.code != 0) {
            System.out.println("发生错误，错误码为：" + myJsonParse.header.code);
            System.out.println("本次请求的sid为：" + myJsonParse.header.sid);
            webSocket.close(1000, "");
        }
        List<Text> textList = myJsonParse.payload.choices.text;
        for (Text temp : textList) {
            System.out.print(temp.content);
            totalAnswer=totalAnswer+temp.content;
        }
        if (myJsonParse.header.status == 2) {
            // 可以关闭连接，释放资源
            System.out.println();
            if(canAddHistory()){
                RoleContent roleContent=new RoleContent();
                roleContent.setRole("assistant");
                roleContent.setContent(totalAnswer);
                historyList.add(roleContent);
            }else{
                historyList.remove(0);
                RoleContent roleContent=new RoleContent();
                roleContent.setRole("assistant");
                roleContent.setContent(totalAnswer);
                historyList.add(roleContent);
            }
            wsCloseFlag = true;
            totalFlag=true;
        }
    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        super.onFailure(webSocket, t, response);
        try {
            if (null != response) {
                int code = response.code();
                System.out.println("onFailure code:" + code);
                System.out.println("onFailure body:" + response.body().string());
                if (101 != code) {
                    System.out.println("connection failed");
                    System.exit(0);
                }
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    // 鉴权方法
    public static String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {
        URL url = new URL(hostUrl);
        // 时间
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        // 拼接
        String preStr = "host: " + url.getHost() + "\n" +
                "date: " + date + "\n" +
                "GET " + url.getPath() + " HTTP/1.1";
        // System.err.println(preStr);
        // SHA256加密
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
        mac.init(spec);

        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        // Base64加密
        String sha = Base64.getEncoder().encodeToString(hexDigits);
        // System.err.println(sha);
        // 拼接
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);
        // 拼接地址
        HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder().//
                addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8))).//
                addQueryParameter("date", date).//
                addQueryParameter("host", url.getHost()).//
                build();

        // System.err.println(httpUrl.toString());
        return httpUrl.toString();
    }

    //返回的json结果拆解
    class JsonParse {
        Header header;
        Payload payload;
    }

    class Header {
        int code;
        int status;
        String sid;
    }

    class Payload {
        Choices choices;
    }

    class Choices {
        List<Text> text;
    }

    class Text {
        String role;
        String content;
    }
    class RoleContent{
        String role;
        String content;

        public String getRole() {
            return role;
        }

        public void setRole(String role) {
            this.role = role;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }
    }
}